package com.gxa.shop.servlet.category;

import com.gxa.shop.bean.dto.CategoryQueryPage;

import com.gxa.shop.bean.pojo.Category;

import com.alibaba.fastjson.JSON;
import com.gxa.shop.commons.r.R;
import com.gxa.shop.service.category.CategoryService;
import com.gxa.shop.service.category.impl.CategoryServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.List;

/**
 * com.gxa.shop.bean.servlet.category
 * User: zjy
 * Date: 2024/12/17 14:33
 * motto:   逆水行舟不进则退
 * Description:
 * Version: V1.0
 */
@WebServlet(name = "CategoryFindByPageServlet",value = "/category/findPage")
public class CategoryFindByPageServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        // 获取并验证请求参数
        String str_page = req.getParameter("page");
        String str_limit = req.getParameter("limit");
        String categoryName = req.getParameter("categoryName");

            // 创建查询实体

            CategoryQueryPage categoryQueryPage = new CategoryQueryPage();

            // 判断是否有参数并处理
            if (str_page != null && !str_page.trim().isEmpty()) {
                try {
                    categoryQueryPage.setPage(Integer.parseInt(str_page.trim()));
                } catch (NumberFormatException e) {
                    categoryQueryPage.setPage(1);
                }
            }

            if (str_limit != null && !str_limit.trim().isEmpty()) {
                try {
                    categoryQueryPage.setLimit(Integer.parseInt(str_limit.trim()));
                } catch (NumberFormatException e) {
                    categoryQueryPage.setLimit(5);
                }
            }

            categoryQueryPage.setCategoryName(categoryName);

            // 初始化服务层对象
            CategoryService categoryService = new CategoryServiceImpl();

            // 满足条件的总条数
            Long total = categoryService.findByTotal(categoryQueryPage);

            // 当前页码的数据，默认为空列表
            List<Category> list = Collections.emptyList();
            if (total > 0) {
                list = categoryService.findByPage(categoryQueryPage);
            }

            // 构建响应数据
            R r = R.ok().addData("total", total).addData("list", list);

            // 响应对象
            PrintWriter writer = resp.getWriter();
            String result = JSON.toJSONString(r);
            System.out.println("FindByPageServlet: " + result);
            writer.write(result);
            writer.flush();
            writer.close();
        }
}